/*
 * grid widget
 */
Qlsolution.widgets.grid = {
	
	/*
	 * widget settings
	 */
	limit: 25,
	
	/*
	 * create/load
	 */
	load: function(settings){
		var paramsData = new Object();
		paramsData['id_node'] = settings.idNode;
		paramsData['limit'] = Qlsolution.widgets.grid.limit;
		paramsData['page'] = settings.page;
		$.ajax({
			type: 'post',
			url: settings.storeUrl,
			data: 'params=' + $.toJSON(paramsData),
			dataType: 'json',
			success: function(msg){
				Qlsolution.widgets.grid.setContent(settings, msg);
			}
		});
	},

	/*
	 * set content grid
	 */
	setContent: function(settings, msg){
		var gridData = msg.results,
			gridCount = msg.count,
			pagesCount,
			paginationCls;
		$(settings.cls + ' .elementContent').html('<table/>');
		$(settings.cls + ' .elementHeader span.numbers').html(gridCount);
		//head
		if(gridData.length > 0){
			$(settings.cls + ' .elementContent table').append('<thead><tr>');
			for(var key in gridData[0]){
				$(settings.cls + ' .elementContent table').append('<th>' + key + '</th>');
			}
			$(settings.cls + ' .elementContent table').append('</tr></thead><tbody>');
		}
		//body
		for (var i = 0; i < gridData.length; i++){
			$(settings.cls + ' .elementContent table tbody').append('<tr>');
			for(var key in gridData[0]){
				if(gridData[i][key] == null){
					gridData[i][key] = '';
				}
				$(settings.cls + ' .elementContent table tbody tr:last').append('<td>' + gridData[i][key] + '</td>');
			}
			$(settings.cls + ' .elementContent table tbody').append('</tr>');
		}
		$(settings.cls + ' .elementContent table tbody').append('</tbody>');
		//pagination
		$(settings.cls + ' .elementContent table').after('<ul class="pagination"/>');
		pagesCount = (Math.ceil(msg.count / Qlsolution.widgets.grid.limit));
		for(var i=0; i<pagesCount; i++){
			paginationCls = '';
			if((i+1) == settings.page){
				paginationCls = 'active';
			}
			$(settings.cls + ' .elementContent ul.pagination').append('<li titile="Go to page ' + (i+1) + '" class="' + paginationCls + '">' + (i+1) + '</li>');
		}
		Qlsolution.widgets.grid.pagination(settings);
	},
	
	pagination: function(settings){
		$(settings.cls + ' .elementContent ul.pagination li').unbind('click');
		$(settings.cls + ' .elementContent ul.pagination li').click(function(){
			settings.page = parseInt($(this).html());
			Qlsolution.widgets.grid.load(settings);
		})
	},

	start: function(settings){
		Qlsolution.widgets.grid.load(settings);
	}

};